package com.service.impl;

import com.POJO.Subject;
import com.mapper.SubjectMapper;
import com.service.SubjectService;
import com.util.MybatisConfig;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * SubjectServiceImpl是SubjectService的具体实现类，
 * 提供对科目信息的各种操作，如获取所有科目、新增科目、更新科目和删除科目等。
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    private SubjectMapper subjectMapper;
    private SqlSession sqlSession;

    // 初始化sqlSession和subjectMapper
    private void openSession(){
        sqlSession = MybatisConfig.getSession();
        subjectMapper = sqlSession.getMapper(SubjectMapper.class);
    }

    /**
     * 获取所有科目
     * @return 科目列表
     */
    @Override
    public List<Subject> getAllSubjects() {
        openSession();
        try {
            return subjectMapper.getAllSubjects();
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据教师ID获取所教授的科目
     * @param teacherId 教师ID
     * @return 科目列表
     */
    @Override
    public List<Subject> getSubjectsTeacherId(int teacherId) {
        openSession();
        try {
            return subjectMapper.getSubjectsByTeacherId(teacherId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 新增科目
     * @param subject 科目对象
     */
    @Override
    public void insertSubject(Subject subject) {
        openSession();
        try {
            subjectMapper.insertSubject(subject);
            sqlSession.commit();
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 更新科目
     * @param updateSubject 更新后的科目对象
     */
    @Override
    public void updateSubject(Subject updateSubject) {
        openSession();
        try {
            subjectMapper.updateSubject(updateSubject);
            sqlSession.commit();
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 删除科目
     * @param subjectId 科目ID
     */
    @Override
    public void deleteSubject(int subjectId) {
        openSession();
        try {
            subjectMapper.deleteSubject(subjectId);
            sqlSession.commit();
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }
}
